package com.netdisk.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.netdisk.dao.Dao;
import com.netdisk.entity.Capacity;

/**
 * 磁盘容量Dao类
 * 
 * @author chenlong 2013-4-13
 */
@Repository(value = "capacityDao")
public class CapacityDao extends Dao<Capacity> {
	@Override
	public void save(Capacity obj) {
		Session session = sessionFactory.getCurrentSession();
		session.save(obj);
	}

	@Override
	public void update(Capacity obj) {
		Session session = sessionFactory.getCurrentSession();
		session.update(obj);
	}

	@Override
	public void delete(Capacity obj) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(obj);
	}

	@Override
	public List<Capacity> findAll() {
		Session session = sessionFactory.getCurrentSession();
		List<Capacity> Capacitys = null;
		Capacitys = session.createQuery("from Capacity").list();
		return Capacitys;
	}

	@Override
	public Capacity findById(String id) {
		Session session = sessionFactory.getCurrentSession();
		List<Capacity> Capacitys = null;
		Capacity Capacity = null;
		Query query = session.createQuery("from Capacity where id=:id");
		query.setString("id", id);
		Capacitys = query.list();
		if (!Capacitys.isEmpty()) {
			Capacity = Capacitys.get(0);
		}
		return Capacity;
	}

	@Override
	public List<Capacity> findByTop(int from, int max) {
		Session session = sessionFactory.getCurrentSession();
		List<Capacity> Capacitys = null;
		Query query = session.createQuery("from Capacity");
		query.setFirstResult(from);
		query.setMaxResults(max);
		Capacitys = query.list();
		return Capacitys;
	}
	
	public Capacity findByOwnerId(String ownerId) {
		List<Capacity> Capacitys = null;
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Capacity where ownerId=:ownerId");
		query.setString("ownerId", ownerId);
		Capacitys = query.list();
		Capacity cap =  Capacitys.get(0);
		return cap;
	}
	public Capacity findByCompanyId(String companyId) {
		List<Capacity> Capacitys = null;
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Capacity where companyId=:companyId");
		query.setString("companyId", companyId);
		Capacitys = query.list();
		Capacity cap =  Capacitys.get(0);
		return cap;
	}
	
	public Long countCompanyCapcityUsed(String companyId){
		Session session = sessionFactory.getCurrentSession();
		Query query = session
				.createQuery("select sum(alreadyUse) from Capacity where companyId=:companyId");
		query.setString("companyId", companyId);
		return (Long)query.uniqueResult();
	}
}
